<template>
  <div class="customerservice">
    <van-nav-bar title="小思同学" class="navbar" fixed>
      <template #left>
        <van-icon name="arrow-left" class="back" @click="back" />
      </template>
    </van-nav-bar>
    <div class="talkbox">
      <ul class="ul">
        <li class="lili">
          <van-image
            round
            width="1.1rem"
            height="1.1rem"
            fit="cover"
            src="https://img01.yzcdn.cn/vant/cat.jpeg"
            class="kefuimg"
          />
          <div class="aa">hi, 你好! 我是小思</div>
        </li>
        <li
          v-for="(item, index) in list"
          :key="index"
          :class="{ lis: item.name == 'user' }"
          class="lili"
        >
          <van-image
            round
            width="1.1rem"
            height="1.1rem"
            fit="cover"
            :src="photo(item.name)"
            class="kefuimg"
            :class="img(item.name)"
          />
          <div :class="name(item.name)">{{ item.msg }}</div>
        </li>
      </ul>
    </div>
    <van-cell-group class="talk">
      <van-field
        v-model="value"
        autocomplete="“off”"
        label=""
        placeholder="说点什么"
        ref="field"
      >
        <template #right-icon><span @click="emit">发送</span></template>
      </van-field>
    </van-cell-group>
  </div>
</template>

<script>
import { io } from 'socket.io-client'
import { mapState } from 'vuex'
let socket = null
export default {
  // 组件名称
  name: 'customerservice',
  // 组件参数 接收来自父组件的数据
  props: {},
  // 局部注册的组件
  components: {},
  // 组件状态值
  data () {
    return {
      value: '',
      list: JSON.parse(window.localStorage.getItem('talk', this.list)) || [],
      Y: 0
    }
  },
  computed: {
    ...mapState(['userinfo']),
    // 展示客服或者用户消息时所对应的动态class样式
    name () {
      return function (value) {
        if (value == 'kefu') {
          return 'aa'
        } else if (value == 'user') {
          return 'bb'
        }
      }
    },
    // 展示客服或者用户头像时所对应的动态class样式
    img () {
      return function (value) {
        if (value == 'user') {
          return 'userimg'
        }
      }
    },
    photo () {
      // 展示客服还是用户头像
      return function (value) {
        if (value == 'kefu') {
          return 'https://img01.yzcdn.cn/vant/cat.jpeg'
        } else if (value == 'user') {
          return this.userinfo.photo
        }
      }
    }
  },
  methods: {
    back () {
      this.$router.push('/layout/mine')
    },
    // 发送消息
    async emit () {
      if (this.value !== '') {
        socket.emit('message', {
          msg: this.value,
          timestamp: +new Date()
        })
        this.list.push({ name: 'user', msg: this.value })
        window.localStorage.setItem('talk', JSON.stringify(this.list))
        this.value = ''
        this.$nextTick(() => {
          this.$refs.field.$el.querySelector('input').focus()
          this.tobottom()
        })
      }
    },
    // 滚动功能,获取到ul里最后一个li,把它滚动到屏幕可视区内,behavior: "smooth"添加动画效果
    tobottom () {
      let item = document.querySelector('.ul')
      let lastitem = item.lastElementChild
      lastitem.scrollIntoView({ behavior: "smooth" })
    }
  },
  created () {
    // 创建客户端 websocket 的实例
    socket = io('http://toutiao.itheima.net', {
      query: {
        token: this.token
      },
      transports: ['websocket']
    })
    // 建立连接的事件
    socket.on('connect', () => {
      console.log('与服务器建立了连接')
    })

    // 接收到消息的事件
    socket.on('message', data => {
      console.log(data);
      // 把服务器发送过来的消息，存储到 list 数组中
      this.list.push({ name: 'kefu', msg: data.msg })
      window.localStorage.setItem('talk', JSON.stringify(this.list))
      this.$nextTick(() => {
        this.tobottom()
      })
    })
  },
  deactivated () {
    // 关闭连接
    socket && socket.close()

    // 销毁 websocket 实例对象
    socket = null
  },
  // 重新回到小思同学页面后自动显示到最后一条消息
  activated () {
    let item = document.querySelector('.ul')
    let lastitem = item.lastElementChild
    lastitem.scrollIntoView({})
  }
}
</script>
<style scoped>
.customerservice {
  position: absolute;
  left: 0;
  top: 0;
  box-sizing: border-box;
  padding-top: 46px;
  padding-bottom: 44px;
  width: 100%;
  height: 100%;
}
.talkbox {
  overflow-y: scroll;
  height: 100%;
  width: 100%;
  background-color: #fafafa;
}
.back {
  color: #fff;
  font-size: 18px;
}
.talk {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  overflow: hidden;
}
li {
  padding: 12px;
}
li div {
  display: inline-block;
  max-width: 70%;
  word-break: break-all;
  line-height: 1.6;
}
.kefuimg {
  vertical-align: middle;
  float: left;
}
.userimg {
  float: right;
  vertical-align: middle;
  position: relative;
  right: 0;
}
.aa {
  position: relative;
  padding: 12px;
  background-color: #e0effb;
  border: 1px solid #c2d9ea;
  font-size: 14px;
  border-radius: 5px;
  margin-left: 16px;
}

.aa::before {
  content: '';
  width: 6px;
  height: 6px;
  position: absolute;
  top: 12px;
  left: -5px;
  border-top: 1px solid #c2d9ea;
  border-right: 1px solid #c2d9ea;
  background: #e0effb;
  transform: rotate(-135deg);
}
.bb::after {
  content: '';
  width: 6px;
  height: 6px;
  position: absolute;
  top: 12px;
  right: -4px;
  border-bottom: 1px solid #c2d9ea;
  border-left: 1px solid #c2d9ea;
  background: #e0effb;
  transform: rotate(-135deg);
}
.bb {
  position: relative;
  max-width: 70%;
  margin-right: 12px;
  padding: 12px;
  float: right;
  background-color: #e0effb;
  border: 1px solid #c2d9ea;
  font-size: 14px;
  border-radius: 5px;
  margin-left: 16px;
  text-align: left;
}
.lis {
  overflow: hidden;
}
</style>
